/**
 * 接口主函数
 * @param {Object} ctx HTTP上下文
 * @param {Object} db 数据管理器,如: { next: async function{}, ret: {} }
 * @return {Object} 执行结果
 */
async function main(ctx, db) {
	// 获取请求参数
	var req = ctx.request;
	var {
		query,
		body
	} = req;

	var {
		user_id,
		project_id,
		car_id
	} = query;
	var search;
	var plug = this.plugin();
	if (plug) {
		var options = plug.get_options();
		if (!project_id) {
			// 如果没有项目ID，则从插件配置中获取
			project_id = options.project_id;
		}
		search = options.generative_rules || "project_id={project_id}&car_id={car_id}";
	}
	var db1 = db.new("tool_move_car", "car_id");
	var car;
	if (car_id) {
		car = await db1.getObj({
			car_id
		});
	}
	if (!car) {
		if (!user_id) {
			// 如果没有用户ID，则从session中获取
			var user = await this.get_state(ctx, db);
			if (user) {
				user_id = user.user_id;
			}
		}
		car = await db1.getObj({
			user_id,
			project_id
		});
		if (!car) {
			car = await db1.getObj({
				user_id
			});
			if (!car) {
				var bl = await db1.add({
					car_number: "粤X·10000",
					name: "X先生",
					phone: "15800000000",
					project_id,
					user_id
				});
				if (bl > 0) {
					car = await db1.getObj({
						user_id,
						project_id
					});
				}
				if (!car) {
					return $.ret.error(10000, "获取信息失败！");
				}
			}
		}
		else {
			car = await db1.getObj({}, "car_id desc");
			car = Object.assign({}, car, {
				project_id,
				car_id: car.car_id + 1,
				user_id: 0,
				name: "",
				phone: "",
				car_number: ""
			});
		}
	}
	if (project_id && !car.project_id) {
		car.project_id = project_id;
	}
	project_id = car.project_id;
	car_id = car.car_id;
	search = search.replace("{project_id}", project_id).replace("{car_id}", car_id).replace("{id}", car_id);
	return $.ret.obj({
		search
	});
	return $.ret.error(10000, "获取信息失败！");
};

exports.main = main;